import Taro, { useEffect, useState, useMemo, useDidShow } from '@tarojs/taro'
import { View, Text, Image } from '@tarojs/components'
import m from 'moment'
import './index.scss'

// components
import CashList from "../../components/cashList";
import NoData from '../../components/noData'
import Poster from "../../components/poster";

// api
import api from '../../api/index';

// utils
import getLoginInfo from "../../utils/getLoginInfo";

// constance
import { WITHDRAW_THRESHOLD} from '../../constances/constances'

export default function Cash() {
  const [inviteUserList, setInviteUserList] = useState([])
  const [balance, setBalance] = useState(0)
  // const [reward, setReward] = useState(0)
  const [user, setUser] = useState({})
  const [isPosterVisible, setIsPosterVisible] = useState(false)

  useDidShow(async () => {
    const userData = getLoginInfo();
    if(!userData) {
      return
    }
    setUser(userData)
    const data = await api.user.getInvitation({
      start: 0,
      end: 9
    });
    if (data.code > 0) {
      setInviteUserList(JSON.parse(data.data).inviteUserList)
    }

    // const _reward = await api.user.getReward();
    // if (_reward) {
    //   setReward(_reward / 100)
    // }

    getBalance()

  })

  async function getBalance() {
    const data  = await api.user.getUserBalance()
    if(data.code > 0) {
      setBalance(data.data / 100)
    }
  }

  // const sumReward = useMemo(() => {
  //   if (inviteUserList.length > 0) {
  //     let sum = 0;
  //     inviteUserList.map(item => {
  //       sum = sum + item.reward_cash_cent
  //     })
  //
  //     return  sum / 100
  //   }
  //
  //   return 0
  // }, [inviteUserList])

  const isCanWithDraw = useMemo(() => {
    return balance > 100
  }, [balance])

  const listData = useMemo(() => {
    return inviteUserList.map(item => {
      return {
        avatar: require('../../assets/180x180defalut_avatar@2x.png'),
        name: item.mobile.replace(/^(\d{3})\d{4}(\d+)/,"$1****$2"),
        desc: m(item.register_date).format('YYYY-MM-DD'),
        num: item.reward_cash_cent / 100
      }
    })
  }, [inviteUserList])

  // const memberNum = useMemo(() => {
  //   if (reward) {
  //     if (isCanWithDraw) {
  //       return inviteUserList.length
  //     } else {
  //       return (WITHDRAW_THRESHOLD - sumReward) / reward
  //     }
  //   } else {
  //     return 999
  //   }
  // }, [inviteUserList, reward])

  function goWithDraw() {
    if (!isCanWithDraw) {
      Taro.showToast({
        icon: 'none',
        title: '未达到提现条件！'
      })
    } else {
      Taro.navigateTo({
        url: `/pages/withdraw/index`
      })
    }
  }

  function goInvitation() {
    Taro.navigateTo({
      url: `/pages/invitation/index`
    })
  }

  console.log(balance)

  return (
    <View className='cash-page'>
      {
        user.token && isPosterVisible && (
          <Poster
            user={user}
            visible={isPosterVisible}
            onCancel={() => setIsPosterVisible(false)}
          />
        )
      }

      <View className='header'>
        <Text className='text'>奖励规则:每成功邀请一位好友购买千读VIP可获 20 ~ 50 元红包</Text>
        <Image className='img' src={require('../../assets/hongbao750X576@2x.png')} />
        {
          !isCanWithDraw && (
            <View className='desc'>还差<Text className='yellow'>{ 100 - balance } 元</Text>就可提现</View>
          )
        }

        {
          isCanWithDraw && (
            <View className='desc'>已获<Text className='yellow'> { balance } 元</Text>红包</View>
          )
        }
        <View className='condition'>满 { WITHDRAW_THRESHOLD } 元红包即可提取现金哦~</View>
      </View>

      <View className='cash-list-container'>
        <View className='header'>
          <View className='more'>
            <Image className='img' src={require('../../assets/right_arrow24X24@2x.png')} />
            <Text className='text' onClick={() => goInvitation()}>更多</Text>

          </View>
          <View className='title-container'>
            <View className='line' />
            <View className='title'>成功邀请好友</View>
            <View className='line' />
          </View>
          {/*<View className='sum-coin'>已成功获得{sumReward}红包</View>*/}
        </View>

        <View className='cash-list-wrapper'>
          {
            listData.length > 0 ? (
              <CashList listData={listData} />
            ) : (
              <View style={{ marginTop: '20px' }}>
                <NoData desc='你还没邀请过好友哦~' />
              </View>
            )
          }
        </View>

        <View className='footer-container'>
          <View className='footer'>
            <View className='text'>
              据说每转发3个群，成功率高达90%
            </View>

            <View className='btn-container'>
              <View className='btn friend' onClick={() => setIsPosterVisible(true)}>邀请好友</View>
              <View className='btn cash' onClick={() => goWithDraw()}>我要提现</View>
            </View>
          </View>
        </View>

      </View>
    </View>
  )
}

Cash.config = {
  navigationBarTitleText: '好友返现',
}
